package room

import (
	"errors"
	"server/common"

	"github.com/mitchellh/mapstructure"
	"github.com/sirupsen/logrus"
)

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *RoomService) handleRegisterServiceReq(msg common.Message, from common.ServiceInfo,
	connId string) error {
	LOG().WithFields(logrus.Fields{
		"msg":    common.ToJson(msg),
		"from":   from,
		"connId": connId,
	}).Info("Handling Register Service Request")

	var data common.RegisterServiceReqData
	if err := mapstructure.Decode(msg.Data, &data); err != nil {
		return errors.New("failed to decode register service request data: " + err.Error())
	}

	if err := s.mediaMgr.RegisterService(data, connId); err != nil {
		LOG(msg.Rid).WithError(err).Error("failed to register media service")
		return err
	}

	LOG(msg.Rid).Info("Media service registered successfully")

	res := common.Message{
		Cmd: common.REGISTER_SERVICE_RES,
		Rid: msg.Rid,
		Data: common.ResMsgData{
			Code: 0,
			Msg:  "success",
		},
	}
	if err := s.dispatcher.Dispatch(res, s.serviceInfo, from, connId); err != nil {
		LOG(msg.Rid).WithError(err).Error("failed to dispatch register service response")
	}

	return nil
}
